package org.jash.exam.view

import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.example.exam.databinding.ActivityExamBinding
import com.example.lib_base.mvvm.BaseActivity
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import org.jash.exam.ExamViewModel
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Timer
import kotlin.concurrent.timerTask
@AndroidEntryPoint
@Route(path = "/exam/ExamActivity")
class ExamActivity : BaseActivity<ActivityExamBinding, ExamViewModel>() {
    private var isCarded = false
    lateinit var timer: Timer
    private var morningCheckIn: String? = null
    private var afternoonCheckIn: String? = null
    private var isMorningCarded = false
    private var isAfternoonCarded = false

    override fun initView() {
        // 顶部栏返回
        binding.back.setOnClickListener { finish() }
        // 刷新按钮
        binding.refresh.setOnClickListener {  }

        // 时间刷新
        val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        timer= Timer()
        timer.schedule(timerTask {
            lifecycleScope.launch {
                binding.tvTime.setText(vm.gettime(System.currentTimeMillis()))
                binding.tvDate.text=sdf.format(System.currentTimeMillis())
            }
        },0,1000)
        // 上班打卡
        binding.btnCard.setOnClickListener {
            if (!isMorningCarded) {
                morningCheckIn = sdf.format(System.currentTimeMillis())
                isMorningCarded = true
                binding.btnCard.text = "下班打卡"
                ToastUtils.showShort("上班打卡成功")
            } else if (!isAfternoonCarded) {
                afternoonCheckIn = sdf.format(System.currentTimeMillis())
                isAfternoonCarded = true
                binding.btnCard.isEnabled = false
                binding.btnCard.text = "已打卡"
                // 两次都打卡后才发起网络请求
                val status = getStatus(morningCheckIn, afternoonCheckIn)
                val map = mutableMapOf<String, Any>()
                map["userId"] = 1
                map["location"] = "天津八维八维"
                map["morningCheckIn"] = morningCheckIn ?: ""
                map["afternoonCheckIn"] = afternoonCheckIn ?: ""
                map["status"] = status
                map["currentLocation"] = "天津市"
                vm.checkIn(map)
            }
        }

        // 位置与GPS（模拟）
        binding.tvLocation.text = "当前位置"
        binding.tvAddress.text = "北京市朝阳区望京 SOHO T1 商务中心"
        binding.tvGps.text = "GPS信号良好"
        binding.ivLocation.setOnClickListener {
            ARouter.getInstance().build("/exam/MAPActivity").navigation()
        }
    }

    override fun initData() {
        vm.checkInSuccess.observe(this) {
            binding.btnCard.isEnabled = false
            binding.btnCard.text = "已打卡"
            ToastUtils.showShort("打卡数据已提交")
        }
    }
    private fun getStatus(morning: String?, afternoon: String?): String {
        // 只要有一次打卡为null，直接返回"缺勤"
        if (morning.isNullOrEmpty() || afternoon.isNullOrEmpty()) return "缺勤"
        val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        val morningTime = sdf.parse(morning)
        val afternoonTime = sdf.parse(afternoon)
        val calendar = Calendar.getInstance()
        calendar.time = morningTime
        val morningHour = calendar.get(Calendar.HOUR_OF_DAY)
        val morningMinute = calendar.get(Calendar.MINUTE)
        calendar.time = afternoonTime
        val afternoonHour = calendar.get(Calendar.HOUR_OF_DAY)
        val afternoonMinute = calendar.get(Calendar.MINUTE)
        // 上班打卡判断
        val isLate = morningHour > 8 || (morningHour == 8 && morningMinute > 30)
        // 下班打卡判断
        val isEarly = afternoonHour < 17
        return when {
            isLate && isEarly -> "迟到早退"
            isLate -> "迟到"
            isEarly -> "早退"
            else -> "正常"
        }
    }

}